package com.example.social.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.social.common.BusinessException;
import com.example.social.entity.KAnonymityConfig;
import com.example.social.mapper.KAnonymityConfigMapper;
import com.example.social.service.KAnonymityConfigService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class KAnonymityConfigServiceImpl extends ServiceImpl<KAnonymityConfigMapper, KAnonymityConfig> implements KAnonymityConfigService {

    @Override
    public KAnonymityConfig getCurrentConfig() {
        return lambdaQuery()
                .eq(KAnonymityConfig::getEnabled, true)
                .orderByDesc(KAnonymityConfig::getUpdateTime)
                .last("LIMIT 1")
                .one();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateConfig(KAnonymityConfig config) {
        if (config.getId() == null) {
            throw new BusinessException("配置ID不能为空");
        }
        
        if (config.getKValue() == null || config.getKValue() < 2) {
            throw new BusinessException("K值必须大于等于2");
        }
        
        if (config.getStrategy() == null || config.getStrategy().isEmpty()) {
            throw new BusinessException("匿名化策略不能为空");
        }
        
        updateById(config);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void toggleConfig(Long configId, Boolean enabled) {
        KAnonymityConfig config = getById(configId);
        if (config == null) {
            throw new BusinessException("配置不存在");
        }
        
        // 如果要启用当前配置，先禁用其他配置
        if (enabled) {
            lambdaUpdate()
                    .set(KAnonymityConfig::getEnabled, false)
                    .ne(KAnonymityConfig::getId, configId)
                    .update();
        }
        
        // 更新当前配置状态
        config.setEnabled(enabled);
        updateById(config);
    }
} 